var express = require('express');
var router = express.Router();
var config = require('./config.json');
var fs = require('fs');
var waterfall = require("async-waterfall");
var path = require("path");
var logger = require('log4js').getLogger();
var EventProxy = require('eventproxy');
var dirs = require('./dirs.js').getDirs();
var xml2js = require('xml2js');
var X2JPaser = new xml2js.Parser();
var builder = new xml2js.Builder();
var platform = require('os').platform();
var workspace_dirs = require('./dirs.js').workspace_dirs;
var cloneGitRepository = require('./gitoper.js').cloneGitRepository;
var removeDir = require('./common/removeDir.js');
var simpleGit = require('simple-git')();
var request = require('request');
var rmdirAllSync = require('./common/tools.js').rmdirAllSync;
var link = require('./target.js').link;
var copy = require('./target.js').copy;
var url = require('url');
var messageAgent = require("./common/message.js");
var uuid = require('uuid');
var decompress = require('decompress');
var decompressUnzip = require('decompress-unzip');
var local_repos = config.local_repo_addr;
var sdp_config = require('./sdp_config.json');
var android_build = require("./build/android_build.js");
var tools = require('./common/tools.js');
var builder_url = url.format(config.app.builder);
var spaces_url = builder_url + '/spaces';
var copy_dir = require('copy-dir');
var zip = require('./common/zip.js');

var downloadGoods = function(version, fileName, type, callback) {
    request(config.store.store_private + '/store/query_download?name=' + fileName + '_' + version, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var body = JSON.parse(body);
            if (body && body.data && body.data.url) {
                logger.info("get down_load_uri:" + body.data.url);
                request.get(body.data.url).on('response', function (response) {
                    if (response.statusCode != 200) {
                        exe_callback("未知的错误，下载失败", null, callback);
                    } else {
                        logger.info("downloading...");
                        var dependency_dir = path.join(local_repos, fileName + "_" + version);
                        var zip_path = path.join(local_repos, fileName + "_" + version + ".zip");
                        var writeStream = fs.createWriteStream(zip_path);
                        response.pipe(writeStream);
                        writeStream.on('close', function () {
                            //依赖下载后 先解压到fileName目录下，如果是mk 需要读取目录后再次解压
                            //依赖下载为zip文件后，根据不同类型解压
                            var epc = new EventProxy();
                            epc.after("file_existed", 1, function () {
                                if (type == sdp_config.goods_type.core_node) {
                                    fs.createReadStream(zip_path).pipe(fs.createWriteStream(path.join(dependency_dir, fileName + "_" + version + ".zip")));
                                    logger.info("download success");
                                    exe_callback(null, null, callback);
                                } else {
                                    decompress(zip_path, dependency_dir, {
                                        plugins: [
                                            decompressUnzip()
                                        ]
                                    }).then(function (data) {
                                        if (data.length == 0) {
                                            logger.error("解压文件出错");
                                        } else {

                                            //根据不同的类型对商品进行处理
                                            if (type == sdp_config.goods_type.MK || type == "app_plugin") {
                                                logger.info("unzip_target");
                                                fs.readdir(dependency_dir, function (err, array) {
                                                    if (err) {
                                                        return exe_callback(err, data, callback);
                                                    }

                                                    array.map(function (filename, i) {
                                                        //解压文件
                                                        decompress(path.join(dependency_dir, filename), dependency_dir, {
                                                            plugins: [
                                                                decompressUnzip()
                                                            ]
                                                        }).then(function (data) {
                                                            if (data.length == 0) {
                                                                exe_callback("解压文件出错", data, callback);
                                                                return false;
                                                            } else {
                                                                fs.unlink(path.join(dependency_dir, filename), function (err, data) {
                                                                    if (err) {
                                                                        return exe_callback("删除临时文件出错", data, callback);
                                                                    }
                                                                    logger.info("解压完成");
                                                                    logger.info("download success");
                                                                    exe_callback(null, data, callback);
                                                                    //epc.emit("download_success");
                                                                });
                                                            }
                                                        });
                                                    });
                                                });
                                            } else {
                                                //解压文件
                                                logger.info("download success");
                                                exe_callback(null, data, callback);
                                            }
                                        }
                                    });
                                }
                            })
                            fs.exists(dependency_dir, function (exists) {
                                if (!exists) {
                                    fs.mkdir(dependency_dir, function (err) {
                                        if (err) {
                                            return exe_callback(err, data, callback);
                                        }
                                        epc.emit("file_existed");
                                    });
                                } else {
                                    removeDir.remove(dependency_dir, function (err) {
                                        if (err) {
                                            return exe_callback(err, null, callback);
                                        }
                                        fs.mkdir(dependency_dir, function (err) {
                                            if (err) {
                                                return exe_callback(err, null, callback);
                                            }
                                            epc.emit("file_existed");

                                        });

                                    });
                                }
                            });
                        });
                    }
                }).on('error', function (err) {
                    exe_callback(err, null, callback);
                });
            } else {
                exe_callback("未知的错误，无法获取下载链接", null, callback);
            }
        } else {
            exe_callback(error, null, callback);
        }
    });
}
exports.downloadGoods = downloadGoods;
function exe_callback(err, data, callback) {
    if (callback && typeof callback === 'function') {
        callback(err, data);
    }
}